package org.grow.auth.controller;

import org.grow.auth.dao.EmployeeMapper;
import org.grow.auth.domain.Employee;
import org.grow.auth.service.AuthPasswordEncoder;
import org.grow.common.exception.MissTargetException;
import org.grow.common.exception.NoAuthException;
import org.grow.common.interceptor.AuthInterceptor;
import org.grow.common.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xwg
 * @CreateDate: 2023/9/21
 */

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private AuthPasswordEncoder authPasswordEncoder;
    @Autowired
    private JwtService jwtService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String username, @RequestParam String password) {
//    step1  check
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            throw new MissTargetException("username is not exist");
        }
        if (!employee.getEnable()) {
            throw new MissTargetException("you account is disabled");
        }
        String passwordFromDB = employee.getPassword();
        String passwordFromFront = authPasswordEncoder.encode(password);
        if (!passwordFromFront.equals(passwordFromDB)) {
            throw new MissTargetException("username password is incorrect");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", employee.getOfficialName());
        String token = jwtService.createToken(map);
        HashMap<String, Object> returned = new HashMap<>();
        returned.put("token", token);
        return returned;

    }

    @GetMapping("/currentUser")
    public String currentUser() {
        return AuthInterceptor.getCurrentUser();
    }


}
